<?php

namespace app\api\library\kuerp;

use Facebook\HttpClients\FacebookCurlHttpClient as BaseFacebookCurlHttpClient;
use Facebook\HttpClients\FacebookCurl;

/**
 * 自定义Facebook Curl HTTP客户端，支持代理配置
 */
class FacebookCurlHttpClient extends BaseFacebookCurlHttpClient
{
    /**
     * @var string 代理地址
     */
    protected $proxy;

    /**
     * @var bool 是否验证SSL证书
     */
    protected $verifySsl;

    /**
     * @param string|null $proxy 代理地址
     * @param bool $verifySsl 是否验证SSL证书
     * @param FacebookCurl|null $facebookCurl
     */
    public function __construct($proxy = null, $verifySsl = true, FacebookCurl $facebookCurl = null)
    {
        $this->proxy = $proxy;
        $this->verifySsl = $verifySsl;
        parent::__construct($facebookCurl);
    }

    /**
     * Opens a new curl connection.
     *
     * @param string $url     The endpoint to send the request to.
     * @param string $method  The request method.
     * @param string $body    The body of the request.
     * @param array  $headers The request headers.
     * @param int    $timeOut The timeout in seconds for the request.
     */
    public function openConnection($url, $method, $body, array $headers, $timeOut)
    {
        $options = [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $this->compileRequestHeaders($headers),
            CURLOPT_URL => $url,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_TIMEOUT => $timeOut,
            CURLOPT_RETURNTRANSFER => true, // Return response as string
            CURLOPT_HEADER => true, // Enable header processing
        ];

        // SSL证书验证配置
        if ($this->verifySsl) {
            $options[CURLOPT_SSL_VERIFYHOST] = 2;
            $options[CURLOPT_SSL_VERIFYPEER] = true;
            $options[CURLOPT_CAINFO] = __DIR__ . '/../../../../vendor/facebook/graph-sdk/src/Facebook/HttpClients/certs/DigiCertHighAssuranceEVRootCA.pem';
        } else {
            $options[CURLOPT_SSL_VERIFYHOST] = 0;
            $options[CURLOPT_SSL_VERIFYPEER] = false;
        }

        // 如果设置了代理，则添加代理配置
        if ($this->proxy) {
            $options[CURLOPT_PROXY] = $this->proxy;
        }

        if ($method !== "GET") {
            $options[CURLOPT_POSTFIELDS] = $body;
        }

        $this->facebookCurl->init();
        $this->facebookCurl->setoptArray($options);
    }
}